﻿using Microsoft.Data.Sqlite;
using SSC.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SSC.Services
{
    /// <summary>
    /// 报警记录服务类，管理报警记录的内存状态和数据库操作
    /// </summary>
    public class AlarmLogService
    {
        // 当前正在报警的项目（不写入数据库，等待结束后再写入）
        private readonly List<AlarmRuntimeEntry> _activeAlarms = new();

        /// <summary>
        /// 报警开始，加入内存，不写数据库
        /// </summary>
        public void StartAlarm(string address, string message)
        {
            if (_activeAlarms.Any(a => a.AlarmAddress == address))
                return; // 已在内存中，不重复加入

            _activeAlarms.Add(new AlarmRuntimeEntry
            {
                AlarmAddress = address,
                AlarmMessage = message,
                StartTime = DateTime.Now
            });
        }

        /// <summary>
        /// 报警结束，写入数据库，移除内存中项
        /// </summary>
        public void EndAlarm(string address)
        {
            var alarm = _activeAlarms.FirstOrDefault(a => a.AlarmAddress == address);
            if (alarm == null) return;

            // 构造完整报警记录
            var log = new AlarmLog
            {
                AlarmAddress = alarm.AlarmAddress,
                AlarmMessage = alarm.AlarmMessage,
                StartTime = alarm.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                EndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                Spare = ""
            };

            // 插入数据库
            string insertQuery = @"
                INSERT INTO tbAlarmLogs 
                (AlarmAddress, AlarmMessage, StartTime, EndTime, Spare) 
                VALUES 
                (@AlarmAddress, @AlarmMessage, @StartTime, @EndTime, @Spare)";

            bool success = App.DatabaseService.Execute(insertQuery, log);
            if (!success)
            {
                throw new Exception("报警记录插入失败");
            }

            _activeAlarms.Remove(alarm);
        }

        /// <summary>
        /// 获取所有当前正在报警的信息（内存中的）
        /// </summary>
        public List<AlarmRuntimeEntry> GetActiveAlarms()
        {
            return _activeAlarms.ToList();
        }

        /// <summary>
        /// 查询历史报警记录（指定时间范围）
        /// </summary>
        public List<AlarmLog> QueryLogs(DateTime from, DateTime to)
        {
            string sql = "SELECT * FROM tbAlarmLogs WHERE StartTime >= @from AND EndTime <= @to";

            return App.DatabaseService.GetAll<AlarmLog>(
                sql,
                new SqliteParameter("@from", from),
                new SqliteParameter("@to", to));
        }
    }
}
